


/* 所有代码必须放在ready方法回调函数内 */
base.ready(function () {
	typeof(CslSharer) !='undefined' && CslSharer.init(base.environment=='prod'?'https://lfyyzcss.cpic.com.cn/tp':'https://lfyyzcss-sit.cpic.com.cn/tp', {keepMarkTime: 4000,zIndex: 2000,});
	if(sessionStorage.getItem('sour') =='hbq'){
			$('.erwei').text('请截图保存，用微信识别二维码');
	}
	var actionConf = require("actionConf");
	var pageAddress = require("pageAddress");
	var jweixin = require("jweixin");

	var policySelect = base.getLocalStorage('selectList', true)[0] || {};
	let state = {
			sessionId: "",
			policyNo: "", //当前复效保单的保单号
			classCode: "", // 险种代码
			sysFlag: "", // 保单系统标识
			modno: "", // 当前复效保单的批单号
			brachId: "", //当前保单的分公司代码
			classFlag: "", //第几套问卷
			qList: [], // 问卷列表
			isTwo: "", // 投被保人是否同为2人  0 不是 1是
			indexImgInfo: "", //投保人问卷填写内容
			obwj: "", //投保人问卷报文
			ihbwj: "", // 被保人问卷报文
			iImgInfo: "", // 被保人填写的答案描述
			oImgInfo: "", // 投保人填写的答案描述
			hbwjIndex0: [], // 投保人转核数据
			hbwjIndex1: [], // 被保人转核数据
			isbehind: 1, // 被保人是否在身边 0 不在身边 1在身边
			oSingxml: "", // 投保人问卷签名
			iSignXml: "", // 被保人问卷签名
			isex: "", // 被保人性别 0是男 1是女
			iage: "", // 被保人年龄
			guardian: "", // 投保人是否是被保人监护人  0 不是 1是
			name2: "", //被保人姓名
			idnum2: "", //被保人证件号
			oprId: "", // 虚拟操作员编号
			role: "O/I", //O/I投被保人,O投保人,I被保人
			hbFlag: "", // 是否需要转核 0 否  1是
			uId: "", // 分享后查询投保人问卷数据的ID
			isAgree: true, // 所填是否真实有效
			aiFlag: 0, // AI小程序开关 0关闭 1打开
			// isSign: 0, // 是否已签名 0 未签 1已签
			isnext: true, // 问卷是否填写完成 true可以下一步   false拦截
			bizNo: "", // 人脸识别业务流程id
	};

	MDclick("reinstateQuestion",sessionStorage.getItem('mdIdnum'),localStorage.ffid,sessionStorage.getItem('userName'),'',localStorage.sessionId,"FX",sessionStorage.getItem('mdpolicy'),"无","无","进入问卷页面");

	$.fn.radioAll = function () {
			var radioChild = $(this).find('span');
			$(radioChild).click(function () {
					if ($(this).hasClass("radio_no2")) {
							$(this).parent().find("span").attr("class", "radio_no2");
							$(this).attr("class", "radio_yes2");
					}
			});
	};
	//初始化问券页面
	function initQuestion(list) {
			//告知信息
			var hbwjQ = list;
			var html = $('.Q_list .lh-30 tr').eq(0);
			$('.Q_list .lh-30').html('');
			// $('#age').val(jsonObj.info[0].age);
			// $('#sex').val(jsonObj.info[0].sex);
			var sex = state.isex;
			var age = state.iage;
			var k = 0;
			var tmp = "";
			var map = {}, idMap = {};
			for (var i = 0; i < hbwjQ.length; i++) {
					tmp = "";
					var cln4 = html.clone(true);
					cln4.attr("rel", i);
					$('.Q_list .lh-30').append(cln4);
					if (hbwjQ[i].isBb == '0') {
							$('.lh-30 tr').eq(i).find('.radio_blo2').remove();
					}
					var flag = "",
							reg = /^[a-zA-Z]+$/;
					if (reg.test(hbwjQ[i].question.substring(0, 1))) {
							if (i > 0 && reg.test(hbwjQ[i - 1].question.substring(0, 1)) && (hbwjQ[i].question.substring(0, 1) == "A")) {
									flag = k + 1 + "、";
									k++;
							} else {
									flag = "";
							}
					} else {
							flag = k + 1 + "、";
							k++;
					}

					var info = "";
					if (reg.test(hbwjQ[i].question.substring(0, 1))) {
							info = hbwjQ[i].isPart + "-" + map[hbwjQ[i].isPart] + hbwjQ[i].question.substring(0, 2);
							if (i > 0 && (hbwjQ[i].question.substring(0, 1) == "A") && reg.test(hbwjQ[i - 1].question.substring(0, 1))) {
									var index = idMap[hbwjQ[i].isPart];
									if (index == null) {
											idMap[hbwjQ[i].isPart] = "1";
									} else {
											idMap[hbwjQ[i].isPart] = parseInt(index) + 1;
									}
							} else {
									var index = idMap[hbwjQ[i].isPart];
									if (index == null) {
											idMap[hbwjQ[i].isPart] = "1";
									}
							}

					} else {
							map[hbwjQ[i].isPart] = flag;
							info = hbwjQ[i].isPart + "-" + flag

							var index = idMap[hbwjQ[i].isPart];
							if (index == null) {
									idMap[hbwjQ[i].isPart] = "1";
							} else {
									idMap[hbwjQ[i].isPart] = parseInt(index) + 1;
							}
					}
					info = info + "-" + idMap[hbwjQ[i].isPart];
					$('.lh-30 tr th').eq(i).html(flag);
					$('.message_Que').eq(i).html(hbwjQ[i].question);
					$('.message_Que').eq(i).attr('isPart', hbwjQ[i].isPart);
					$('tr').eq(i).find('span').eq(0).find('span').eq(0).attr('id', 'checkid' + i);
					$('tr').eq(i).find('img').attr('info', info);
					//单选调用
					$(".radio_blo2").radioAll();
					if (sex == "0" && $('.message_Que').eq(i).attr('isPart') == "3") {  //性别女性，问卷第三部分女性补充告知，同一人
							tmp = "none";
					}
					if (age > 4 && $('.message_Que').eq(i).attr('isPart') == "4") {  //四岁以下，问卷第三部分女性补充告知，同一人
							tmp = "none";
					}
					$('.lh-30 tr').eq(i).css('display', tmp);
					info = info + "-" + idMap[hbwjQ[i].isPart] + "-" + (i + 1) + "|";
					$('.lh-30 tr th').eq(i).html(flag);
					$('.message_Que').eq(i).html(hbwjQ[i].question);
					$('.message_Que').eq(i).attr('isPart', hbwjQ[i].isPart);
					$('tr').eq(i).find('span').eq(0).find('span').eq(0).attr('id', 'checkid' + i);
					$('tr').eq(i).find('img').attr('info', info);
					//单选调用
					$(".radio_blo2").radioAll();
					if (sex == "0" && $('.message_Que').eq(i).attr('isPart') == "3") {  //性别女性，问卷第三部分女性补充告知，同一人
							tmp = "none";
					}
					if (age > 4 && $('.message_Que').eq(i).attr('isPart') == "4") {  //四岁以下，问卷第三部分女性补充告知，同一人
							tmp = "none";
					}
					$('.lh-30 tr').eq(i).css('display', tmp);
			}
			setTimeout(function () {
					state.myScroll.refresh();
			}, 400);
	}
	function initPage() {
			state.show_tb = location.href.getQueryString('show_tb');
			state.insured = location.href.getQueryString('insured');
			state.insuredBehind = location.href.getQueryString('insuredBehind');
			state.insuredLinkId = location.href.getQueryString('linkId');

			if (state.show_tb) { // 被保人查看投保人填写情况
					let insuredPage = base.getLocalStorage("insuredPage", true);
					$(".show_question_hide").addClass("displayN");
					$(".bottom_main04").show();
					$(".bottom_main02").hide();
					initQuestion(insuredPage.list);
					writeInfo(insuredPage.tbAns);

			} else if (state.insured) { // 分享后被保人进来
					let insuredPage = base.getLocalStorage("insuredPage", true);
					let info = insuredPage.info[0];
					state.oprId = insuredPage.oprId;
					state.sysFlag = insuredPage.sysFlag;
					state.brachId = insuredPage.branchId;
					state.role = "I";
					state.classFlag = insuredPage.classFlag;
					state.qList = insuredPage.list;
					state.idnum2 = info.idnum2;
					state.name2 = info.name2
					state.policyNo = info.policyNo;
					state.isex = info.sex;
					state.iage = info.age;
					initQuestion(insuredPage.list);
			} else if (state.insuredBehind) { // 被保人在身边时进来
					let questionPage = base.getLocalStorage('questionPage', true);
					state.hbwjIndex0 = questionPage.hbwjIndex0;
					state.obwj = questionPage.obwj || state.obwj;
					firstIn()
			} else {
					firstIn()
			}
			// 4.	若投保人，被保人为同一人时，填写被保人问卷，签字栏展示“被保人签名”，由投保人（即被保人）签字
			if (state.isTwo == "0") {
					$('.signature_main .s_top').html('被保险人签字');
					$('.Q_title').html("投保人/被保人");
			} else if (state.isTwo == "1" && state.iage < 18 && state.guardian) {
					$('.Q_title').html("投保人/被保人");
					$('.signature_main .s_top').html('投保险人签字');
					$('.sign_tips').removeClass('displayN');
					state.role = "O/I";
			} else if (state.insured) {
					state.role = "I";
					$('.Q_title').html("被保人");
					$('.signature_main .s_top').html('被保险人签字');
			} else if (state.insuredBehind) {
					state.role = "O/I";
					$('.Q_title').html("被保人");
					$('.signature_main .s_top').html('被保险人签字');
			} else {
					let insureUser = base.getLocalStorage('list', true) ? base.getLocalStorage('list', true).reinstates : {}
					state.role = "O";
					state.iage = insureUser.age;
					state.isex = insureUser.sex;
					$('.Q_title').html("投保人");
					$('.signature_main .s_top').html('投保险人签字');
			}

			function firstIn() {
					let policyInfo = base.getLocalStorage('selectList', true)[0] || {};
					if (base.getLocalStorage('list', true)) {
							state.oprId = base.getLocalStorage('list', true)["reinstates"]['oprId'];
					}
					state.sessionId = base.getLocalStorage('sessionId')
					state.policyNo = policyInfo.policyNo;
					state.classCode = policyInfo.classCode;
					state.isTwo = policyInfo.isTwo;
					state.brachId = policyInfo.branchId;
					state.isex = policyInfo.isex;
					state.iage = policyInfo.iage;
					state.sysFlag = policyInfo.sysFlag;
					state.guardian = policyInfo.guardian;
					state.name2 = policyInfo.name2;
					state.idnum2 = policyInfo.idnum2;
					let params = {
							"classCode": state.classCode || "13360100",
							"sessionId": state.sessionId,
							"sysFlag": state.sysFlag || "0",
					}
					let busiApplySystem = sessionStorage.getItem('busiApplySystem')||'';
					let outDate =  sessionStorage.getItem('inTenDate')?JSON.parse(sessionStorage.getItem('inTenDate')):{};
					// if(busiApplySystem == 'P17' && outDate.inTenDate == '1'){
					if(policyInfo.xztype && policyInfo.xztype=="3" && outDate && outDate.inTenDate =="1" && outDate.ages){
							params.busiApplySystem = busiApplySystem;
							params.ages = outDate.ages; // 0 >=18、1 4<ages<18、2 <=4
					}
					base.ajax.post({
							url: actionConf.reinstate.questionnaire,
							data: params,
							success: function (res) {
									let list = res.questionnaire.list || []
									initQuestion(list);
									state.classFlag = res.questionnaire.classFlag;
									state.qList = res.questionnaire.list;
							}
					})
			}
			testAnySign(state);//初始化
			state.myScroll = new iScroll('wrapper', { hScrollbar: false, vScrollbar: false });
	}
	initPage();
	getSwitch()
	//判断用户是否是操作后返回,如果是则展示用户填写数据
	function writeInfo(pageInfo) {
			var info = pageInfo;
			var arr = info.split("|");
			console.log(arr);

			$('.lh-30 tr').each(function (ind, ele) {
					$(ele).find('.radio_no2').addClass('change');
					$(ele).find('.radio_yes2').addClass('change');
					$(ele).find('input').each(function (inddd, elel) {
							$(elel).addClass('change');
							$(elel).addClass('cag');
					});
					$('.change').attr('infoCheck', '0');
			});

			for (var i = 0; i < arr.length; i++) {
					$('.change').each(function (indd, element) {
							//$(element).attr("disabled",true);
							//$(element).text(arr[indd]);
							$(element).attr('infoCheck', arr[indd]);
							if ($(element).attr('infoCheck') == '●') {
									if ($(element).hasClass('radio_yes2')) {

									} else if ($(element).hasClass('radio_no2')) {
											$(element).removeClass('radio_no2');
											$(element).siblings().removeClass('radio_yes2').addClass('radio_no2');
											$(element).addClass('radio_yes2');
									}

							}
							if ($(element).hasClass('cag')) {
									if ($(element).val() == '') {
											$(element).val(arr[indd]);
									}
									//
									if ($(element).attr('infoCheck') == '●') {
											$(element).attr('checked', true);

									}
							}
					});
			}

	}
	// 投保人保存问卷
	function saveQuestion() {
			base.ajax.post({
					url: actionConf.reinstate.getQuestion,
					data: {
							"accXT": "0004",
							"bqtype": "FX",
							"brachId": state.brachId,
							"classFlag": state.classFlag,
							"indexImgInfo": state.indexImgInfo,
							"modno": base.getLocalStorage('modno'),
							"obwj": state.obwj,
							"oimgInfo": state.oimgInfo,
							"policyNos": state.policyNo,
							"sessionId": state.sessionId,
							"zhInfo": JSON.stringify(state.hbwjIndex0)
					},
					success: function (res) {
							if (res.resCode === "0000") {
									state.uId = res.id;
									base.setLocalStorage('questionPage', state, true);
									if (state.isbehind) {
											setTimeout(function () {
													base.gotoUrl(pageAddress["问卷"] + `?insuredBehind=1`);
											}, 1000);
											MDclick("reinstateQuestion",sessionStorage.getItem('mdIdnum'),localStorage.ffid,sessionStorage.getItem('userName'),"",localStorage.sessionId,"FX",sessionStorage.getItem('mdpolicy'),"无","无","下一步-被保人问卷页面");
											return
									}
									showDiv('open2')
							}
					}
			})
	}

	// 投保人问卷保存
	function clickSubmint() {
			var flag = ques();    //判断页面题目是否全部完成
			if (!flag) {
					base.toast('请将您的健康告知填写完整!')
					return
			}
			if (!state.isAgree) {
					base.toast("请勾选信息真实申明");
					return
			}
			getVoucherInfo();
			if (!state.isnext) {
					return
			}
			getImgVal();
			if (!state.isnext) {
					return
			}
			baowen();

			if ($('#xss_20').attr('rel') == $("#xss_20").attr('src')) {
					base.toast("请先填写签名");
					return
			}

			base.setLocalStorage('questionPage', state, true)
			getModno('FX');
	}
	//获取批单号
	function getModno(bqtype) {
			localStorage.modno = "";
			var modno = "";
			let flag1 = '1'
			let sour = sessionStorage.getItem('sour');
			if(sour == 'hbq')
					flag1 = '6'
			var json = {
					flag: flag1,
					appId: "",
					bqtype: bqtype,
					sessionId: state.sessionId

			};
			base.ajax.post({
					url: actionConf.common.getModno,
					data: json,
					success: function (jsonObj) {
							var rescode = jsonObj.resCode;
							if (rescode == "9999") {
									modno = "9999";
									alert('获取批单号失败');
							} else {
									var pidanno = jsonObj.result;
									var sysData = jsonObj.sysData;
									if (rescode == "0000") {
											modno = pidanno;
											state.modno = modno;
											localStorage.modno = modno;
											//自定义埋点
											MDclick("reinstateQuestion",sessionStorage.getItem('mdIdnum'),localStorage.ffid,sessionStorage.getItem('userName'),modno,localStorage.sessionId,"FX",sessionStorage.getItem('mdpolicy'),"无","无","问卷提交");
											if (state.isTwo == '0' || state.isTwo == "1" && state.guardian == "1" && state.iage < 18 || state.insured || state.insuredBehind) {
													saveCore()
											} else {
													showDiv('open4');
											}
									} else {
											modno = "9999";
											alert('获取批单号失败');
									}
							}
					}
			});
	}
	//获取问卷填写情况
	function getVoucherInfo() {
			var printMap = new Map();
			var hbwjVal = '';
			state.isnext = true;
			var indexStr = "";
			$('.radio_blo2 img').each(function (index, ele) {
					if ($(ele).css("display") != "none" && $(ele).attr("src") == "./img/fill_icon.png") {
							var info = $(ele).attr("info");
							//ind = ind.slice(7,8);
							if ($(ele).closest('tr').find('th').text() != '') {
									var b = $(ele).val() || $(ele).attr('value');
									if (b == "") {
											if (state.isnext) {
													state.isnext = false;
													var mes = info.split("-")[1];
													base.toast("请填写第" + mes.substring(0, mes.length - 1) + "题");
													return;
											}
									} else {
											hbwjVal = $(ele).val() || $(ele).attr('value');
											var partInfo = printMap.get(info.split("-")[0]);
											if (partInfo == null) {
													printMap.set(info.split("-")[0], info.split("-")[2] + "、" + hbwjVal);
											} else {
													printMap.set(info.split("-")[0], partInfo + ";" + info.split("-")[2] + "、" + hbwjVal);
											}

											indexStr += info.split("-")[4] + hbwjVal + "-";
											localStorage.setItem("indexImgInfo", indexStr.substring(0, indexStr.length - 1));
									}
							}
					}

			});
			var reValue = "";
			if (printMap.get("1")) {
					reValue += "第一部分:" + printMap.get("1") + "\n";
			}
			if (printMap.get("2")) {
					reValue += "第二部分:" + printMap.get("2") + "\n";
			}
			if (printMap.get("3")) {
					reValue += "第三部分:" + printMap.get("3") + "\n";
			}
			if (printMap.get("4")) {
					reValue += "第四部分:" + printMap.get("4") + "\n";
			}
			if (!state.isnext) {
					return;
			}
			localStorage.setItem("oImgInfo", reValue);

			state.indexImgInfo = indexStr.substring(0, indexStr.length - 1);
			if (state.isTwo == "0" || (state.isTwo == "1" && state.iage < 18 && state.guardian)) {
					state.oImgInfo = reValue;
					state.iImgInfo = reValue;
			} else if (state.insured || state.insuredBehind) {
					state.iImgInfo = reValue;
			} else {
					state.oImgInfo = reValue;
			}
			return {
					oImgInfo: reValue,
					indexImgInfo: indexStr.substring(0, indexStr.length - 1)
			}
	}
	// 转核数据提交核心
	function saveCore() {
			base.ajax.post({
					url: actionConf.reinstate.getCore,
					data: {
							"accXT": "0004",
							"bqtype": "FX",
							"oprId": state.oprId,
							"branch": state.brachId,
							"hbwjIndex0": JSON.stringify(state.hbwjIndex0),
							"hbwjIndex1": JSON.stringify(state.hbwjIndex1),
							"idnum2": state.idnum2,
							"modno": state.modno,
							"name2": state.name2,
							"policyNo": state.policyNo,
							"questionType": state.classFlag,
							"role": state.role,
							"sessionId": state.sessionId,
							"sysFlag": state.sysFlag
					},
					success: function (res) {
							// debugger
							if (res.hbFlag === "1" || policySelect.isYjOrGj == '1') {
									state.hbFlag = "1";
									showDiv('open3');
							} else {
									// 保存问卷
									state.hbFlag = "0";
									base.setLocalStorage('questionPage', state, true);
									if (!state.insured) {
											setTimeout(function () {
													base.gotoUrl(pageAddress["复效银行卡"])
											}, 1000);
											MDclick("reinstateQuestion",sessionStorage.getItem('mdIdnum'),localStorage.ffid,sessionStorage.getItem('userName'),"",localStorage.sessionId,"FX",sessionStorage.getItem('mdpolicy'),"无","无","下一步-跳转银行卡页面");
									} else {
											history.go(-1)
									}

							}
					}
			})
	}

	// 调用AI平台小程序二维码
	function getAIQrCode() {
			let time = new Date().Format("yyyy-MM-dd hh:mm:ss");
			state.bizNo = "bdgj" + Date.now() + /\d{4}$/.exec(Math.random());
			base.ajax.post({
					url: actionConf.reinstate.authentication,
					data: {
							"bizNo": state.bizNo,
							"time": time,
							"name": state.name2.replace(/\s+/g, ""),
							"pid": state.idnum2,
							"imageFlag": 1,
							"type": 1,
							"faceType":"FX",
					},
					success: function (res) {
							if (res.code === "0000") {
									let myurl = pageAddress["AI小程序"] + `?${res.para}`
									setQrcode(myurl)
							}
					}
			})
			function setQrcode(myurl) {
					var qrcode = new QRCode(document.getElementById("qrcode"), {
							width: 275,
							height: 275
					});
					qrcode.makeCode(myurl);
					//在小米或者华为手机上生成的二维码是通过canvas展示的，img标签被隐藏,所以需要特殊处理一下，将canvas标签隐藏，拿到生成的url放到img里面再展示出来
					var myCanvas = document.getElementsByTagName('canvas')[2];
					var img = convertCanvasToImage(myCanvas);
					$("#qrcode").empty();
					$("#qrcode").append(img);
			};
			//将canvas返回的图片添加到image里
			function convertCanvasToImage(canvas) {
					var image = new Image();
					image.src = canvas.toDataURL("image/png");
					return image;
			}
	}
	$(".close_open5").on('click', function () {
			closeDiv('open5');
			getAIresult();
	})
	// 获取认证结果
	function getAIresult() {
			base.ajax.post({
					url: actionConf.reinstate.authenticationQuery,
					data: {
							"bizNo": state.bizNo,
					},
					success: function (res) {
							saveAiInfo(res)
							if (res.code == "0000") {
									// 保存投保人问卷继续填写被保人问卷
									saveQuestion()
							} else {
									base.alert(res.message)
							}
					}
			})
	}
	function saveAiInfo(res = {}) {
			base.ajax.post({
					url: actionConf.reinstate.aiSave,
					data: {
							"bizno": state.bizNo,
							"modual": 'FXWJ',
							"custname": state.name2,
							"custidnum": state.idnum2,
							"errmsg": res.message,
							"resultfx": res.code,
							"issuccess": res.result ? '0': '1',
					},
					showLoading: false,
					success: function (res) {
							if (res.resCode != "0000") {
									base.alert(res.message)
							}
					}
			})
	}
	// 获取AI认证开关
	function getSwitch() {
			base.ajax.post({
					url: actionConf.reinstate.switch,
					data: {},
					showLoading: false,
					success: function (res) {
							state.aiFlag = res;
					}
			})
	}

	$(".goBackPre").on("click", function () {
			if (state.insured) {
					history.go(-1)
			} else {
					//base.gotoUrl(pageAddress["复效列表"])
					window.history.back();
			}
	})
	$(".goBackPreInsured").on("click", function () {
			history.go(-1)
	})

	$('#submit').on('click', function () {
			clickSubmint()
	})

	$('.zh_sure').on('click', function () {
			base.setLocalStorage('questionPage', state, true)
			setTimeout(function () {
					base.gotoUrl(pageAddress["复效银行卡"])
			}, 1000);
			MDclick("reinstateQuestion",sessionStorage.getItem('mdIdnum'),localStorage.ffid,sessionStorage.getItem('userName'),"",localStorage.sessionId,"FX",sessionStorage.getItem('mdpolicy'),"无","无","下一步-跳转银行卡页面");
	})
	$('.isbehind').on('click', function () {
			closeDiv('open4')
			if (state.isbehind) {
					MDclick("reinstateQuestion",sessionStorage.getItem('mdIdnum'),localStorage.ffid,sessionStorage.getItem('userName'),"",localStorage.sessionId,"FX",sessionStorage.getItem('mdpolicy'),"无","无","被保人在身边");
					// 如果在身边,判断ai开关,调用小程序二维码
					if (state.aiFlag == 1 && sessionStorage.getItem('sour') !='hbq') {//慧保全进来  不需要二次人脸识别，在小程序端已经识别过了
							base.ajax.post({
									url: actionConf.faceAI.toggleH5Switch,
									data: {
											from: 'wx',
											bqtype: "FX"
									}, success: function (resp) {//h5人脸识别开关
											if (resp.resCode == "0000" && resp.message == "0") {
													base.setLocalStorage('questionPage', state, true);
													var callBackUrl = location.href;
													callBackUrl = callBackUrl.split("?")[0].replace("reinstateQuestion.html","faceAIQuery.html");
													let param = {
															name    : state.name2.replace(/\s+/g, ""),
															idnum   : state.idnum2,
															bqtype  : 'FX',
															from    : 'wx',
															callBackUrl : callBackUrl,
													}
													getFaceAIH5(param);
											}else{
													getAIQrCode();
													showDiv("open5");
											}
									}, error: function (res) {
											getAIQrCode();
											showDiv("open5");
									}
							});
					} else {
							MDclick("reinstateQuestion",sessionStorage.getItem('mdIdnum'),localStorage.ffid,sessionStorage.getItem('userName'),"",localStorage.sessionId,"FX",sessionStorage.getItem('mdpolicy'),"无","无","被保人不在身边");
							// 保存投保人问卷继续填写被保人问卷
							saveQuestion()
					}
			} else {
					MDclick("reinstateQuestion",sessionStorage.getItem('mdIdnum'),localStorage.ffid,sessionStorage.getItem('userName'),"",localStorage.sessionId,"FX",sessionStorage.getItem('mdpolicy'),"无","无","被保人不在身边");
					// 如果不在身边调用投保人问卷保存,再调用微信分享,分享惠保全小程序
					saveQuestion()
			}
	})
	// $('.share_to_bb').on('click', function () {
	//     // 分享给被保人
	//     base.weixinShare.chooseImage({
	//         callback: function (id) {
	//             alert(id)
	//         }
	//     })
	// })

	//判断是否是小程序环境
	function doMiniProgram(callback) {
			try {
					//小程序环境设置分享
					var ua = window.navigator.userAgent.toLowerCase();
					//判断是否是微信环境
					if (ua.match(/MicroMessenger/i) == 'micromessenger') {
							//微信环境
							jweixin.miniProgram.getEnv(function (res) {
									if (res.miniprogram) {
											callback();
									}
							})
					}
			}
			catch (ex) {
					console.log(ex);
			}
	}

	function saveQuery(callback) {
			base.ajax.post({
					url: actionConf.reinstate.queryKeyField,
					data: {
							uid: state.uId,
							pid: state.idnum2,
							name: state.name2,
							systemSource: "bdgj",
							module: "FX"
					},
					success: function (res) {
							if (res.resCode == "0000") {
									callback(res.sessionId)
							}
					}
			})
	}

	$('.btn_sharetobb').on('click', function () {
			// 分享给被保人
			closeDiv('open2')
			$('.share_misk').show()
			var str = `uid=${state.uId}&name=${state.name2}&pid=${state.idnum2}`
			var imageUrl= 'https://bdgj.cpic.com.cn/base/img/zhiye.png';

			if(base.environment == "prod"){

					imageUrl= 'https://bdgj.cpic.com.cn/base/img/zhiye.png';
			}else{
					imageUrl= 'https://bdgj-sit.cpic.com.cn/base/img/zhiye.png';
			}

			doMiniProgram(function () {
					saveQuery(function (linkid) {
							jweixin.miniProgram.postMessage({ data: { title: '保单复效-被保险人问卷填写', path: '/pages/index/main?scene='+linkid, imageUrl: imageUrl } })
					})
			})


			base.weixinShare.shareMessageToFriend({
					title: "保单复效-被保险人问卷填写",
					desc: "请在24:00点前完成问卷填写",
					link: pageAddress['慧保全分享'] + `?${encodeURIComponent(str)}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
					imgUrl: imageUrl, // 分享图标
					callback: function () {

					}
			})
	})
	$('.share_misk').on('click', function () {
			$('.share_misk').hide();
			base.confirm({
					content: "请确认您已分享给被保人",
					callback: function () {
							base.setLocalStorage('questionPage', state, true);
							setTimeout(function () {
									base.gotoUrl(pageAddress["复效银行卡"])
							}, 1000);
							MDclick("reinstateQuestion",sessionStorage.getItem('mdIdnum'),localStorage.ffid,sessionStorage.getItem('userName'),"",localStorage.sessionId,"FX",sessionStorage.getItem('mdpolicy'),"无","无","下一步-跳转银行卡页面");
					},
					cancelCallback: function () {
							showDiv("open2");
					}
			})
	})

	$('.radio_blo3 p').on('click', function () {
			if (!$(this).hasClass('radio_yes3')) {
					$(this).addClass('radio_yes3').removeClass('radio_no3');
					$(this).siblings('p').removeClass('radio_yes3').addClass('radio_no3');
					if ($(this).text() == "在身边") {
							state.isbehind = 1;
					} else {
							state.isbehind = 0;
					}
			}
	})
	$('.chk_bottom .check_blo span').on('click', function () {
			if (!$(this).hasClass('check_yes')) {
					$(this).addClass('check_yes').removeClass('check_no');
			} else {
					$(this).addClass('check_no').removeClass('check_yes');
			}
			state.isAgree = !state.isAgree;
			console.log(state.isAgree)
	})


	// 初始化签名
	// $().esign("canvasEdit", "sign_show", "sign_clear", "sign_ok");
	// $('.signature_main').on('click', function () {
	//     let ClientWidth = document.documentElement.clientWidth;
	//     let ClientHeight = document.documentElement.clientHeight * .75;
	//     $('#canvasEdit').attr({ 'width': ClientWidth, 'height': ClientHeight });
	//     $('#signature_page').removeClass('displayN');
	//     localStorage.setItem('drawFlag', 0)
	//     // $('#sign_show').empty();
	// })
	// $('#sign_ok').on('click', function () {

	//     setTimeout(function () {
	//         console.log(localStorage.getItem('drawFlag'))
	//         if (localStorage.getItem('drawFlag') == 0) {
	//             // $('#sign_show').css({ 'backgroundColor': '' })
	//             base.alert("请填写签名!")
	//             return
	//         }
	//         $('#signature_page').addClass('displayN');
	//         $('#sign_show').css({ 'backgroundColor': '#fff' })
	//         $('#sign_show img').attr({ 'width': '100%', 'height': '100%' })
	//         //判断当前签名人的身份
	//         var xmlVal = $('#sign_show img').attr('src') ? $('#sign_show img').attr('src').split(',')[1] : ""
	//         if (state.role == "O/I") {
	//             base.setLocalStorage('iSignXml', xmlVal)
	//             base.setLocalStorage('oSingxml', xmlVal)
	//         } else if (state.role == "O") {
	//             base.setLocalStorage('oSingxml', xmlVal)
	//         } else {
	//             base.setLocalStorage('iSignXml', xmlVal)
	//         }
	//     }, 500)
	// })
	// $('#sign_clear').on('click', function () {
	//     setTimeout(function () {
	//         // $('#signature_page').addClass('displayN');
	//         // $('#sign_show').css({ 'backgroundColor': '' })
	//         if (state.role == "O/I") {
	//             base.removeLocalStorage('iSignXml')
	//             base.removeLocalStorage('oSingxml')
	//         } else if (state.role == "O") {
	//             base.removeLocalStorage('oSingxml')
	//         } else {
	//             base.removeLocalStorage('iSignXml')
	//         }
	//     }, 500)
	// })
	// $(".go_back_show").on("click", function () {
	//     $('#signature_page').addClass('displayN');
	// })
	/*******************************   CA   ***********************************/
	$("#xss_20").click(function () {
			testPopupDialog(20);
	});
	$('#btnOK').click(function () {
			let signXml = apiInstance.getEncodedSignData();
			// state.isSign = 1;
			if(state.insuredBehind){
					base.setLocalStorage('iSignXml', signXml)
			} else if (state.role == "O/I") {
					base.setLocalStorage('iSignXml', signXml)
					base.setLocalStorage('oSingxml', signXml)
			} else if (state.role == "O") {
					base.setLocalStorage('oSingxml', signXml)
			} else {
					base.setLocalStorage('iSignXml', signXml)
			}
			setTimeout(function () {
					state.myScroll.refresh();
			}, 400);
	});


	document.onreadystatechange = setAlertTitle;
	var apiInstance;

	function setAlertTitle() {
			//document.title = "返回结果";
	}

	//配置模板数据
	function testSetTableData() {
			let policysObj = {
					name: state.name2,
					custId: state.idnum2
			}
			var formData = "{\"bjcaxssrequest\":{\"submitinfo\":[{\"username\":\"" + policysObj.name + "\",\"identitycardnbr\":\"" + policysObj.custId + "\"}]}}";
			var signer = "{\"bjcaxssrequest\":{\"submitinfo\":[{\"username\":\"" + policysObj.name + "\",\"identitycardnbr\":\"" + policysObj.custId + "\"}]}}";

			//var formData = JSON.stringify(formDataBody);
			//记事本续期服务回访表模板信息如下：
			//模板id：3600   （ticketID值为360 ，otherType值为0，）
			//签名规则id: 5100   2240
			var tid = "2240";
			var charset = "utf-8";
			var businessId = "719314ea7b88304004c8ff498";
			var template_serial = "1#4000";
			var channel = "100004";
			var res = apiInstance.setData(13, formData);
			res = apiInstance.setData(14, signer);
			res = apiInstance.setData(15, "hash");
			res = apiInstance.setData(16, "100004");
			apiInstance.setTID("2240");//签名模板ID
			return res;
	}

	//添加签名框
	function testAddSignatureObj(objId, necessary) {
			var context_id = objId;
			var signatureConfig = new SignatureConfig();
			signatureConfig.isNecessary = necessary
			var res = apiInstance.addSignatureObj(context_id, signatureConfig);
			return res;
	}

	function testAnySign(channel) {
			let canvas = document.getElementById("anysignCanvas");
			let context = canvas.getContext("2d");
			context.fillStyle = "white";
			context.fillRect(0, 0, canvas.width, canvas.height);
			var res;
			var callback = function (context_id, context_type, val) {
					if (context_type == CALLBACK_TYPE_START_RECORDING || context_type == CALLBACK_TYPE_STOP_RECORDING) {
							return;
					}
					MDclick("reinstateQuestion",sessionStorage.getItem('mdIdnum'),localStorage.ffid,sessionStorage.getItem('userName'),"",localStorage.sessionId,"FX",sessionStorage.getItem('mdpolicy'),"无","无","问卷签名");
					if (context_type == CALLBACK_TYPE_SIGNATURE) {
							document.getElementById("xss_20").src = "data:image/gif;base64," + val;
					}
					else if (context_type == CALLBACK_TYPE_MASS_SIGNATURE) {
							document.getElementById("xss_30").src = "data:image/gif;base64," + val;
					}
					else if (context_type == CALLBACK_TYPE_ON_PICTURE_TAKEN) {
							document.getElementById("preview").src = "data:image/gif;base64," + val;
					} else if (context_type == CALLBACK_TYPE_ON_MEDIA_DATA) {
							var audio = document.createElement("audio");
							if (audio != null && audio.canPlayType && audio.canPlayType("audio/mpeg")) {
									audio.src = "data:image/gif;base64," + val;
									audio.play();
							}
					}

					setAlertTitle();
					// alert("收到浏览器回调：" + "context_id：" + context_id + " context_type：" + context_type + " value：" + val);
			};//测试回调，将回调数据显示

			apiInstance = new AnySignApi();

			res = apiInstance.initAnySignApi(callback, channel);


			//注册单字签字对象20
			res = testAddSignatureObj(20, true);

			//注册多字签字对象30
			res = testAddSignatureObj(30, false);
			apiInstance.addDataObj(13, new DataObj());//配置数据域13
			apiInstance.addDataObj(14, new DataObj());//配置数据域14
			apiInstance.addDataObj(15, new DataObj());//配置数据域15

			res = apiInstance.commitConfig();
	}


	function testIsReadyToUpload() {
			alert("testIsReadyToUpload :" + apiInstance.isReadyToUpload());
	}

	function testGenData() {
			//alert("data to upload:" + apiInstance.getEncodedSignData());
			var res = document.getElementById('result');

			try {
					res.value = apiInstance.getEncodedSignData();
			}
			catch (err) {
					alert(err);//err.fileName + "," + err.lineNumber + "," + err.message
			}
	}

	function testPopupDialog(context_id) {
			testSetTableData();//设置模板数据

			switch (apiInstance.showSignatureDialog(context_id)) {
					case RESULT_OK:
							break;
					case EC_API_NOT_INITED:
							//alert("信手书接口没有初始化");
							break;
					case EC_WRONG_CONTEXT_ID:
							//alert("没有配置相应context_id的签字对象");
							break;
			}
	}


	function testGetVersion() {
			alert(apiInstance.getVersion());
	}

	function testGetOsInfo() {
			alert(apiInstance.getOSInfo());
	}






	// 签名结束


	// 报文保存接口获取
	function baowen() {
			localStorage.upload = 0;
			var str = ''; var arr = [];
			$(".lh-30 tr").each(function (index, ele) {
					var obj = {};
					var inpVal = '';
					for (var x = 0; x < $(ele).find('input').length; x++) {
							if ($(ele).find('input').eq(x)[0].type == "radio") {
									if ($(ele).find('input').eq(x)[0].checked == true) {
											inpVal += '●' + '|';
									} else {
											inpVal += '' + '|';
									}
							} else if ($(ele).find('input').eq(x)[0].type == "checkbox") {
									if ($(ele).find('input').eq(x)[0].checked == true) {
											inpVal += '●' + '|';
									} else {
											inpVal += '' + '|';
									}
							} else {
									inpVal += $(ele).find('input').eq(x)[0].value + "|";
							}
					}
					obj[index + 1] = inpVal;
					$(ele).find(".radio_blo2").find("span").each(function (iii, ell) {
							let iele = '';
							if ($(ell).hasClass("radio_yes2")) {
									//选择了是打印出●|
									if (iii == '0') {
											iele = '●|' + '|';
											localStorage.upload = 1;
									} else if (iii == '1') {
											iele = '|●' + '|';
									}
									// 判断当前问题是否有输入框
									if (inpVal) {
											obj[index + 1] = iele + inpVal;
									} else {
											obj[index + 1] = iele;
									}
							}

					});
					obj[index + 1] = obj[index + 1].substr(0, obj[index + 1].length - 1);
					arr.push(obj);
			});

			var keys = [];
			for (var x = 0; x < arr.length; x++) {
					for (var property in arr[x])
							keys.push(property);
			}
			var delid = '';
			for (var y = 0; y <= arr.length - 1; y++) {
					for (var x = 0; x < keys.length; x++) {
							if (arr[y][keys[x]] == delid) {
									arr.splice(y, 1);
							}
					}
			}
			var values = [];
			for (var x = 0; x < arr.length; x++) {
					for (var property in arr[x])
							values.push(arr[x][property]);
			}
			for (var m = 0; m < values.length; m++) {

					str += values[m] + '|';
			}
			str = str.substr(0, str.length - 1);

			let outDate =  sessionStorage.getItem('inTenDate')?JSON.parse(sessionStorage.getItem('inTenDate')):{};
			if (state.isTwo == "0" || (state.isTwo == "1" && state.iage < 18 && state.guardian)) {
					state.obwj = str;
					state.ihbwj = str;
			} else if (state.insured || state.insuredBehind) {
					state.ihbwj = str;
			} else {
					state.obwj = str;
			}
			return str;
	}

	// 转核数据获取
	function getImgVal() {
			state.isnext = true;
			var listAnswer = [];
			var partAnswer = {};
			$('.lh-30 tr').each(function (index, ele) {
					if (!$(this).is(":hidden")) {
							var listI = {};
							var rel = $(this).attr("rel");
							if ($(this).find(".radio_blo2").length == 0 || $(this).find(".radio_blo2").is(":hidden")) {
									listI.isYes = "";
							} else {
									if ($(this).find(".radio_blo2").find("span:first").hasClass("radio_yes2")) {
											listI.isYes = "1";
									} else {
											listI.isYes = "0";
									}
							}
							var desc = "";
							if ($(this).find("img").length > 0 && !$(this).find("img").is(":hidden")) {//有详细描述
									var info = $(ele).find("img").attr("info");
									desc = $(this).find("img").val() || $(this).find("img").attr('value');
									if (desc == "" || desc == null) {
											state.isnext = false;
											var mes = info.split("-")[1];
											base.toast("请填写第" + mes.substring(0, mes.length - 1) + "题")
											return;
									}

									var partInfo = info.split("-")[2] + "、" + desc;
									if (!(partAnswer["part" + info.split("-")[0]])) {
											partAnswer["part" + info.split("-")[0]] = [];
									}
									partAnswer["part" + info.split("-")[0]].push(partInfo);
							} else {
									var inputValueArr = [];
									$(this).find("input").each(function () {
											if ($(this).attr("type") == 'radio') {
													if ($(this).is(":checked")) {
															inputValueArr.push($(this).val());
													} else {
															//inputValueArr.push("");
													}
											} else if ($(this).attr("type") == 'checkbox') {
													if ($(this).is(":checked")) {
															inputValueArr.push($(this).val());
													} else {
															//inputValueArr.push("");
													}
											} else {
													var input_val = $(this).val();
													inputValueArr.push($.trim(input_val));
											}
									});
									desc = inputValueArr.join("|");
							}

							listI.FFnumber = state.qList[rel].ffNumber;
							listI.seqId = state.qList[rel].seqid;
							listI.desc = desc;
							listAnswer.push(listI);
					}
			});
			if (state.isTwo == "0" || (state.isTwo == "1" && state.iage < 18 && state.guardian)) {
					state.hbwjIndex0 = listAnswer;
					state.hbwjIndex1 = listAnswer;
			} else if (state.insured || state.insuredBehind) {
					state.hbwjIndex1 = listAnswer;
			} else {
					state.hbwjIndex0 = listAnswer;
			}
			// state.zhInfo = listAnswer;
			return listAnswer;
	}
	//问卷是否填写完整
	function ques() {
			var validateKey = true;
			$(".lh-30 tr").each(function (ind, elx) {
					if ($(elx).find('.radio_blo2').length > 0) {
							//如果是否存在
							$(elx).find(".radio_blo2").find("span").each(function (ii, elle) {
									if ($(elle).hasClass("radio_yes2")) {
											//选择了是，input必须存在值
											if (ii == '0') {
													for (var x = 0; x < $(elx).find('input').length; x++) {
															//选择了是的radio没有填写
															if ($(elx).find('input').eq(x)[0].type == "radio") {

																	if ($(elx).find("input[type='radio']:checked").length > 0) {

																	} else {
																			validateKey = false;
																	}

															} else if ($(elx).find('input').eq(x)[0].type == "checkbox") {
																	if ($(elx).find("input[type='checkbox']:checked").length > 0) {

																	} else {
																			console.log($(elx));
																			validateKey = false;
																	}
															} else {
																	//选择了是的input没有填完整

																	if ($(elx).find('input').eq(x)[0].value == '') {
																			console.log($(elx));
																			validateKey = false;
																	}

															}
													}
											}
									}

							});
					} else {
							//没有选择的input没有填完整
							$(elx).find('input').each(function (inputind, eleinput) {
									if ($(eleinput)[0].value == '' && $(eleinput).parents('tr')[0].style.display == "") {
											// console.log($(eleinput).parents('tr').attr('rel'));
											validateKey = false;
									}
							});
							if ($(elx).find("input[type='radio']").length > 0) {
									if ($(elx).find("input[type='radio']:checked").length > 0) {

									} else {
											validateKey = false;
									}
							}

					}
			});
			if (!validateKey) {
					localStorage.removeItem('info');
					base.toast('请将您的健康告知填写完整!');
			}
			return validateKey;
	}


});

// 选择是并填写详细信息
var imgclass = '';
function showdetail(btn) {
	if (btn.tagName.toLowerCase() === "span") {
			var id = $(btn).attr('id');
			$(btn).parent().find('img').removeAttr("class");
			$(btn).parent().find('img').addClass(id);

			imgclass = $(btn).parent().find('img').attr('class');
	} else {
			imgclass = $(btn).attr('class');
	}

	var html = '';
	// html += "<div class='dk_con_div_p'>";
	html += "<textarea rows='5'  placeholder='你好，最多可输入20个字！' maxlength='20'></textarea>";
	// html += "</div>";
	if ($(btn).closest('tr').find('input').length == 0) {
			$("#detail").html(html);
			showDiv('open1');
	}
	if ($('.' + imgclass).attr('value') != '') {
			var textareaHtml = $('.' + imgclass).attr('value');
			$('textarea').attr('value', textareaHtml);
	}
	if ($(btn).closest('tr').find('input').length == 0) {
			$(btn).parent().find('img').css('display', 'inline-block');
	}

	$('.' + imgclass).attr("onclick", "showdetail(this)");
	$(document).on('click', '.inputOk', function () {
			var textareaHtml = $('#detail textarea').val();
			if (textareaHtml == "") {
					// Alert("请输入描述语！");
					base.toast("请输入描述语！")
					return;
			} else {
					$('.' + imgclass).attr('value', textareaHtml);
					closeDiv('open1');
			}
	});
}
function hidedetail(btn) {
	$(btn).parent().find('img').css('display', 'none');
	$(btn).parent().find('img').attr('value', "");
}

//弹出层调用
function showDiv(id, e) {
	$.openPopupLayer({
			name: id,
			target: id
	});
	//弹出层里下拉框显示$(".open_block select").css({visibility : "visible"});
}

function closeDiv(id) {
	$.closePopupLayer(id);
}

function inputFocusBlur() {

	$(".input").each(function () {
			$(this).focus(function () {

					$('.bottom_main02').css({ 'position': 'static' })
			})

			$(this).blur(function () {

					$('.bottom_main02').css({ 'position': 'fixed' })
			})
	});

}